from helpers.director.shortcut import TablePage,ModelTable,ModelFields,page_dc,director,director_view
from .models import DepartMent,Userinfo
from helpers.func.sqldb.helpers import bulk_update

class DepartMentPage(TablePage):
    def get_label(self):
        return '部门管理'
    def get_template(self, prefer=None):
        return 'jb_admin/table_new.html'
    class tableCls(ModelTable):
        model = DepartMent
        exclude =['path']
        button_edit = True
        
        def dict_head(self, head):
            width  ={
                'name':130,
                'leader':140,
                'parent':140,
            }
            head['width'] = width.get(head['name'])
            return head

class DepartMentForm(ModelFields):
    class Meta:
        model = DepartMent
        exclude = ['path']
    
    #def get_operations(self):
        #ops = super().get_operations()
        #for op in ops:
            #if op['name'] =='save':
                #op['click_express']=''' cfg.show_load()
                #debugger;
                #ex.director_call('worker_is_in_department',{row:scope.ps.vc.row}).then((resp)=>{
                   #if(resp){
                       #cfg.hide_load()
                       #return cfg.confirm(resp.msg)
                   #}
                #}).then(()=>{
                    #cfg.show_load()
                    #scope.ps.vc.submit()
                #}).then(()=>{
                    #cfg.hide_load()
                #})'''
        #return ops
    
    def clean_save(self):
        bb = []
        for inst in self.instance.leader.all():
            inst.userinfo.department = self.instance
            bb.append(inst.userinfo)
        if bb:
            bulk_update(bb,update_fields=['department'])
    
        

@director_view('worker_is_in_department')
def check_is_ok(row):
    leaders= row.get('leader',[])
    not_proper = []
    is_leader = []
    for inst in Userinfo.objects.filter(user_id__in=leaders):
        if inst.department.pk != row.get('pk'):
            not_proper.append(inst.user.first_name)
        if inst.department_leader.all():
            pass
    
    if not_proper:
        return {
            'msg':';'.join(not_proper)+',当前不属于部门【{row.get("name")}】,确认要把他们挪到该部门吗?'
        }

director.update({
    'department':DepartMentPage.tableCls,
    'department.edit':DepartMentForm,
})
        
page_dc.update({
    'department':DepartMentPage
})